/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { InternalAxiosRequestConfig, AxiosRequestConfig } from 'axios'
import { ElLoading } from 'element-plus'
import JSONbig from 'json-bigint'//解决超过 16 位数字精度丢失问题

interface RequestConfig extends InternalAxiosRequestConfig {
  loading?: boolean;
}

const service = axios.create({
  transformResponse: [ function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      //  JSONbig.parse(data)
      return JSON.parse(JSON.stringify(JSONbig.parse(data)))
    } catch (err) {
      // 如果转换失败，则包装为统一数据格式并返回
      return {
        data
      }
    }
  } ]
})
let loading: any
service.interceptors.request.use((config: RequestConfig) => {
  if(config.url?.includes('token')){
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
  }
  const hasLoading = Object.hasOwn(config, 'loading')
  if (!hasLoading || (hasLoading && config.loading === false)) {
    loading = ElLoading.service({ fullscreen: true })
  }
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  config.headers['Accept-Language'] = 'zh-CN,zh;q=0.9,en;q=0.8'
  return config
})
// const specialUrl = [ '/OData', '/token', '/permissions','/identity' ]
const request = async <T = any>(config: AxiosRequestConfig): Promise<Api.Result<T>> => {
  try {
    const { data } = await service.request<Api.Result<T>>(config)
    // if (data.code !== 200 && !specialUrl.find(str => config.url?.includes(str))) {
    //   window.$message.error(data.message)
    // }
    if(loading){
      loading.close()
    }
    return data
  } catch (err: any) {
    if (loading) {
      loading.close()
    }
    console.log(err)
    const { headers,data,status,message } = err.response
    if (headers._abperrorformat){
      window.$message.error(data.error.message)
    }
    if (status === 401) {
      console.log('401')
    } else if (status === 403) {
      console.log('403')
      // if()
    }
    return {
      code: -1,
      message: message || err.response.data.error_description || '',
      data: null as any
    }
  }
}

export default request